package com.baidu.intercepter;

import com.baidu.common.Constant;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String u = request.getRequestURI();
        System.out.println(u);
        if (isContainsNoAuthUrl(u)) {
            request.getSession().getAttribute(Constant.LOGIN_USER);
            response.sendRedirect("login");
            return false;
        } else {
            return true;
        }
    }


    // 2. 需要认证登录的路径， 我们需要 通过request session
    //    通过session来取登录用户
    // 有登录用户
    //      return true
    // 没有登录用户
    //      通过 response 重定向地址

    private boolean isContainsNoAuthUrl(String url){
        Set<String> urlSet = new HashSet<>();
       urlSet.add("/login");
        urlSet.add("/error");
        urlSet.add("/loginSign");
        return urlSet.contains(url);
    }
}
